<template>

  <div class="flex page page-draw-index border-t-4 border-t-[#F8F8FB]">
    <div class="w-91 px-4 py-3 pb-10  bg-white border-r-4 border-r-[#F8F8FB]">
      <div class="hd flex items-center  text-5 font-bold">
        {{ activeWorkflow?.name }}
        <!-- <img src="/icons/draw-icon4.png" alt="图标1" class="m-l-1 w-4 h-4" /> -->
      </div>
      <div class="inputcon" v-show="activeWorkflow?.type == 'text2img'">
        <div class="input-hd">
          <div class="intro text-3 mb-3">
            *文本描述
          </div>
          <textarea type="text" v-model="prompt" class="textarea text-3">
          </textarea>
        </div>
        <div class="input-bd border-box pt-3 text-3 flex justify-between">
          <div class="left flex items-center cursor-pointer ">

            <!-- <img src="/icons/draw-icon5.png" alt="图标1" class="mr-1 w-3 h-3" /> -->
            <span class="text-gray-400">示范</span>
            <span class="ml-1">请输入多个关键词，用逗号隔开</span>
          </div>
          <div class="right text-gray-400">
            {{ prompt.length }}/1000
          </div>
        </div>
      </div>

      <div class="uploadcom0 px-2 py-4" v-if="activeWorkflow?.type == 'upload'">
        <el-upload class="upload-demo" drag v-model:file-list="fileList" ref="upload" :action="uploadUrl"
          list-type="picture" :headers="headers" :before-upload="beforeUpload" :on-preview="handlePictureCardPreview"
          :data="uploadData" :on-remove="handleRemove" :limit="1" :on-success="handleSuccess">

          <el-icon>
            <ElIconUpload />
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>

      <div class="optionImagecon" v-if="activeWorkflow?.type == 'optionImage'">
        <div class="optionImageCon flex flex-wrap">
          <div class="img" v-for="(img, index) in activeWorkflow?.templates" :key="index"
            :class="[{ active: optionImageIndex == index }]" @click="changeOptionImageIndex(index)">
            <img :src="img" alt="" srcset="" class="w-23 h-23 m-1 block">

          </div>
        </div>

      </div>
      <div class="group" v-show="false">
        <div class="group-hd">
          应用
        </div>
        <div class="group-bd styles">
          <div class="group-item stylepic" :class="[{ active: activeWorkflow.workflowId == ls.workflowId }]"
            v-for="(ls, index) in loraStyles" :key="index" @click="changeWorkflowId(ls.workflowId)">

            <img :src="ls.icon" alt="风格图标" class="w-full h-full" />
            <div
              class="style-name text-4 h-8 flex justify-center items-center absolute left-0 bottom-0  w-full text-white">
              {{ ls.name }}</div>
          </div>

        </div>
        <!-- <div class="group-bd option">
          <div class="label">背景移除</div>
        </div> -->
      </div>

      <div class="group" v-show="false">
        <div class="group-hd">
          张数
        </div>
        <div class="group-bd gennum">
          <div class="group-item numitem" :class="[{ active: gennum == 1 }]" @click="changeGennum(1)">1</div>
        </div>
      </div>


      <div class="button">
        <div class="btn-submit" @click="drawImageByPrompt" :class="[{ disable: loading }]">
          <div class="sumbit-hd text-4">立即生成</div>
          <div class="sumbit-hd text-3 font-light">({{ cost }}积分)</div>
        </div>
      </div>
    </div>


    <div class="w-210 bg-white pic-container relative block">

      <div class="emptycon flex-grow flex items-center justify-center w-full h-full" v-if="!comfyTasks.length">

        <div class="empty flex">
          <div class="left">
            <img src="/icons/draw-icon6.png" alt="图标1" class="w-65 h-45" />

          </div>
          <div class="right">
            <div class="intro-hd">生成的图片将会显示在这里</div>
            <div class="intro-bd">应用生成图片时间较长 请耐心等待</div>
          </div>
        </div>
      </div>
      <div class="genpics flex flex-wrap ">
        <div class=" " v-for="(task, index) in comfyTasks" :key="task.prompt_id">

          <ComfyCptTaskItem :taskItem="task" :width="150" :height="150" @clickPubWorkinfo="clickPubWorkinfo" />
        </div>
      </div>


    </div>
  </div>

  <ClientOnly>
    <PublicCptPubWorkInfoModal v-model:visible="pubmodalVisible" :currentTaskInfo="currentTaskInfo"
      @pubworkSuccess="pubworkSuccess" />
  </ClientOnly>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { postAiDrawDS, postAIWorkflowLogs, postOssSign, postSendDrawTask } from '../../service/yapi';
import PublicCptWorkInfoItem from '~/components/public/CptWorkInfoItem.vue';
import PublicCptPubWorkInfoModal from '~/components/public/CptPubWorkInfoModal.vue';
import ComfyCptTaskItem from '~/components/comfy/CptTaskItem.vue';

import type { UploadFile, UploadUserFile } from 'element-plus';
const {
  signIn,
  token,
  data: userInfo,
  status,
  lastRefreshedAt,
  signOut,
  getSession,
} = useAuth();
import { useAppStore } from "~/stores/app";
let app = useAppStore();
let { refreshBalance, toggleLoginModal } = app;
let prompt = ref('白日依山尽')
let gennum = ref(1)
let menuIndex = ref(0)
let cost = computed(() => {
  return gennum.value * 1
})
let genPics = ref([])
let comfyTasks = ref<any>([])


const isDrawing = ref(false);
const autoFetch = ref(true);
const context = ref(null);
const color = ref('#000000');
const size = ref(5);
const drawHistory = ref([]);

const canvas = ref(null);

let loraStyles = ref([
  { name: "迪士尼风格", workflowId: 11, defaultPrompt: "best quality,masterpiece", icon: "https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/api-1.png", type: "upload" },
  {
    name: "“欢度国庆”主题AI绘画", workflowId: 12, defaultPrompt: "best quality,masterpiece", icon: "https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/api-12.jpg", type: 'optionImage',
    templates: [
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-1.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-2.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-3.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-4.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-5.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-6.jpg',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-7.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-8.png',
      'https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/app12/app12-9.png',
    ]
  },
  { name: "3D手办", workflowId: 13, defaultPrompt: "best quality,masterpiece", icon: "https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/api-1.png", type: "upload" },
  { name: "古诗词插图", workflowId: 15, defaultPrompt: "白日依山尽", icon: "https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/api-1.png", type: "text2img" },
  { name: "简笔画", workflowId: 23, defaultPrompt: "best quality,masterpiece", icon: "https://xiaobao2.oss-cn-beijing.aliyuncs.com/comfyui/workflows/api-1.png", type: "upload" },
])
let route = useRoute()

let activeWorkflowId = ref(route.params.id)
let activeWorkflow = computed(() => {
  let match = loraStyles.value.find(ls => ls.workflowId == activeWorkflowId.value)
  return match ? match : { name: "暂未找到应用", workflowId: null, type: "other", templates: [] }
})



let getWorkflowLogs = async () => {
  let res: any = await postAIWorkflowLogs({
    id: activeWorkflowId.value
  })
  if (res.code == 1000) {
    comfyTasks.value = [
      ...comfyTasks.value,
      ...res.data.map((item: any) => {
        return {
          id: item.id,
          prompt_id: item.prompt_id,
          outputPics: item.outputPics,
          workinfos: item.workinfos,
          status: {
            completed: item.outputPics ? true : false
          }
        }
      })
    ]
  }
}

onMounted(() => {

  if (activeWorkflow.value) {
    prompt.value = activeWorkflow.value.defaultPrompt
  }
  getWorkflowLogs()
});
let pubworkSuccess = ({ id }) => {
  pubmodalVisible.value = false
  comfyTasks.value = []

  getWorkflowLogs()
}
const uploadUrl = ref('');
const headers = ref({});
const fileList = ref<UploadUserFile[]>([
])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const getAliyunCredentials = async (file: any) => {
  let res: any = await postOssSign({})
  let { data } = res
  uploadUrl.value = data.host;
  uploadData.value = {
    key: `comfyui/apps/${activeWorkflowId.value}/${generateRandomFileName(file)}`,
    policy: data.policy,
    OSSAccessKeyId: data.OSSAccessKeyId,
    success_action_status: '200',
    signature: data.signature,
  };
  console.log("%c Line:87 🍅 res", "color:#fca650", res);
  console.log('获取上传凭证')
}
let changeWorkflowId = () => {

}
const generateRandomFileName = (file: any) => {
  const extension = file.name.split('.').pop();
  const randomName = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}.${extension}`;
  return randomName;
};
const beforeUpload = async (file: any) => {
  if (!token.value) {
    toggleLoginModal()
    ElMessage.warning('请先登录')
    return false
  }
  // 在上传前获取阿里云凭证
  await getAliyunCredentials(file);


  return true;
};
const handleRemove = (file: UploadFile) => {
  console.log(file)
}
const uploadData = ref({
  key: '',
  policy: '',
  OSSAccessKeyId: '',
  success_action_status: '200',
  signature: '',
});
const handleSuccess = (response: any, file: any, fileList: any) => {
  const baseUrl = 'https://xiaobao2.oss-cn-beijing.aliyuncs.com/';
  file.url = `${baseUrl}${uploadData.value.key}`;
  console.log('上传成功', file.url);
};

const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}

const handleDownload = (file: UploadFile) => {
  console.log(file)
}

let pubmodalVisible = ref(false)
let currentTaskInfo = ref({
  id: ""
})
let clickPubWorkinfo = (pubInfo: any) => {
  let taskItem = pubInfo.taskItem;
  currentTaskInfo.value.id = taskItem.id
  pubmodalVisible.value = true

}
const lastRequestTime = ref(0);

let optionImageIndex = ref(0)
let changeOptionImageIndex = (index: any) => {
  optionImageIndex.value = index

}
let loading = ref(false)
const drawImageByPrompt = async () => {
  if (!token.value) {
    toggleLoginModal()
    return ElMessage.warning('请先登录')
  }
  if (Number(activeWorkflowId.value) == 15 && prompt.value.length < 5) {
    ElMessage.warning('请至少输入五个字');
    return;
  }
  let inputPic;
  if (activeWorkflow.value.type == 'optionImage') {
    if (optionImageIndex.value == -1) {
      return ElMessage.warning('请选择一个模板')
    }
    inputPic = activeWorkflow.value.templates[optionImageIndex.value]
  } else if (activeWorkflow.value.type == 'upload') {
    if (!fileList.value[0]?.url) {
      ElMessage.warning('请先上传图片');
      return;
    }
    if (fileList.value[0]?.url.indexOf('localhost') > -1) {
      ElMessage.warning('请等待图片上传成功');
      return;
    }
    inputPic = fileList.value[0].url
  }

  const currentTime = Date.now();
  if (currentTime - lastRequestTime.value < 10000) {
    ElMessage.warning('时间限制：10秒内只能请求一次');
    return;
  }
  lastRequestTime.value = currentTime;
  loading.value = true

  let res: any = await postSendDrawTask({
    prompt: prompt.value,
    inputPic,
    workflowId: activeWorkflowId.value,

  }).catch(err => {
    console.log("%c Line:220 🥚 err", "color:#42b983", err);

  });
  if (res && res.code == 1000) {
    comfyTasks.value = [
      {
        prompt_id: res.data.prompt_id,
      },
      ...comfyTasks.value,
    ]
    console.log("%c Line:217 🥥 res", "color:#fca650", res);
    refreshBalance()
  } else {
    console.log("%c Line:176 🍬 res", "color:#6ec1c2", res);
    ElMessage.warning(res.message);
  }
  loading.value = false

}
definePageMeta({ auth: false });
</script>

<style lang="scss">
.page-draw-index {
  .icon-container {
    @apply w-15 h-15 cursor-pointer rounded-md flex flex-col items-center justify-center mb-2.5;
    /* 图标之间的间距 */

    .icon-image {
      @apply w-5 h-5;
    }

    .icon-text {
      @apply text-4 m-t-1;
      /* 图标与文字之间的间距 */
    }

    &.active {
      @apply bg-[var(--bg-base)] font-bold;
    }
  }

  .inputcon {
    @apply w-82 bg-[var(--bg-base)] rounded-md mt-3 box-border px-4 py-3;

    .input-hd {


      .textarea {
        @apply w-full h-25 bg-white box-border p-2 rounded-md border-none resize-none;

        &:focus {
          outline: none;
        }
      }
    }


    .input-bd {
      @apply border-t-1 border-color-[CBCED3] mt-2 flex justify-between;
    }
  }

  .group {
    @apply mt-3;

    .group-bd {
      @apply mt-2;
    }

    .styles {
      @apply flex flex-wrap bg-[var(--bg-base)] rounded-md px-2 py-2 box-border;

      .group-item {
        overflow: hidden;
        @apply border-2 border-[var(--bg-base)] w-24 h-24 bg-gray-300 relative rounded-md mx-1 my-2 cursor-pointer;

        &.active {
          @apply border-2 border-[var(--blue-base)];
        }

        &.stylepic {

          .style-name {
            background: rgba(29, 37, 90, 0.46);


          }

        }
      }
    }

    .option {
      @apply flex flex-wrap bg-[var(--bg-base)] rounded-md px-2 py-2 box-border;

    }

    .gennum {
      @apply flex flex-wrap rounded-md px-2 py-2 box-border;

      .numitem {
        @apply bg-[var(--bg-base)] py-2 flex-1 rounded-md text-center m-1 cursor-pointer text-gray-400;

        &.active {
          @apply bg-[var(--blue-base)] text-black;
        }
      }
    }

  }

  .optionImagecon {
    .img {
      border: 1px solid #fff;

      &.active {
        border: 1px solid #2974F6;
      }

    }
  }


  .btn-submit {
    @apply w-full h-13 bg-[var(--blue-base)] rounded-md cursor-pointer text-center py-2;
    line-height: 1.2;
    background: linear-gradient(180deg, #19E8E0 -3%, #2974F6 92%, #2974F6 100%), #FFFFFF;

    &.disable {
      background: #ccc;
      cursor: not-allowed;
    }

    .sumbit-hd {
      @apply text-white;
    }
  }

  .genpic {
    &:hover .btn-append {
      display: block;
    }
  }
}
</style>